package com.stlm2.controller;

import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.service.ActivityService;
import com.stlm2.dems.service.AddressService;
import com.stlm2.dems.service.PurchaseOrderService;
import com.stlm2.dems.service.SeckillGoodsService;
import com.stlm2.util.codecontent.CodeContent;
import net.sf.json.JSONArray;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by apple on 2017.12.22.
 */
@Controller
@RequestMapping("/seckillGoodsC")
public class SeckillGoodsController {

    @Resource
    private SeckillGoodsService seckillGoodsService;
    @Resource
    private UserDao userDao;
    @Resource
    private AddressDao addressDao;
    @Resource
    private AddressService addressService;
    @Resource
    private PurchaseOrderService purchaseOrderService;
    @Resource
    private DdmShopDao ddmShopDao;
    @Resource
    private SeckillGoodsDao seckillGoodsDao;
    @Resource
    private DdmGoodsDao ddmGoodsDao;
    @Resource
    private GoodSpecificationDao goodSpecificationDao;
    @Resource
    private ActivityService activityService;


    /**
     *  前台 查询 秒杀商品
     * ffl
     * 2017-12-22 17:08:09
     * @param sort
     * @param pageNu
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getList.json",produces="application/json;charset=UTF-8")
    public String list(String companyCode,String sort,String pageNu){
        String data = null;
        try {
            data = seckillGoodsService.list(companyCode,sort, pageNu);
        } catch (Exception e) {
            e.printStackTrace();
            return CodeContent.getModelByCode(0, "查询失败", data);
        }
        return data;
    }


    /**
     *  秒杀商品详情
     * ffl
     * 2017-12-26 11:19:21
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getDetail.json",produces="application/json;charset=UTF-8")
    public String seckillGoodsDetail(String companyCode,String id){
        String data = null;
        try {
            data = seckillGoodsService.seckillGoodsDetail(companyCode,id);
        } catch (Exception e) {
            e.printStackTrace();
            return CodeContent.getModelByCode(0, "查询失败", data);
        }
        return data;
    }

    @ResponseBody
    @RequestMapping(value = "/confirmOrder.json", produces = "application/json;charset=UTF-8")
    public String buyRightNow(String companyCode,String token, String id) {

        Map<String, Object> map = new HashMap<String, Object>();
             /*
          * 是否登录
          * */
        if (StringUtils.isEmpty(token)) {
            map.put("code", -1);
            map.put("msg", "token参数不能为空");
            return new JSONObject(map).toString();
        }
        User loginUser = userDao.getByToken(token);
        if (loginUser == null) {
            map.put("code", -1);
            map.put("msg", "请登录");
            return new JSONObject(map).toString();
        }

        if (StringUtils.isEmpty(id)) {
            map.put("code", 0);
            map.put("msg", "token参数不能为空");
            return new JSONObject(map).toString();
        }

    /*
        * 处理用户收货地址问题
        * */
        //用户是否已经设置收货地址
        Address userAddress = addressDao.getByUserId(loginUser.getId());
        if (userAddress == null) {
            map.put("addressType", 1);
            map.put("addressContent", "请填写您的收货地址");
        } else {
        /*
        *地址参数精简
        * */
            Map<String, Object> addressMap = new HashMap<String, Object>();
            addressMap = addressService.buildModel(userAddress);
            map.put("address", addressMap);
            map.put("addressType", 2);
        }
        /*
        * 处理商品清单以及清单的商品数据、商品数量、清单的总价
        * */
        Map<String, Object> mapPre = new HashMap<String, Object>();
        mapPre = seckillGoodsService.confirmOrder(loginUser.getId(),id);
        if (!mapPre.get("code").toString().equals("1")) {
            return CodeContent.getModelByCode(Integer.valueOf(mapPre.get("code").toString()), mapPre.get("msg").toString(), null);
        }
        Map<String, Object> goodsMap = (Map<String, Object>) mapPre.get("goods");
        BigDecimal totalMoney= (BigDecimal) mapPre.get("totalMoney");
        BigDecimal saveMoney = (BigDecimal) mapPre.get("saveMoney");
        map.put("goods", goodsMap);

        /*
        * 合计金钱
        * */
        map.put("totalMoney",totalMoney);
        map.put("saveMoney", saveMoney);
        map.put("seckillGoodsId",id);
        map.put("seckillState",activityService.SeckillActivityState(companyCode));
        map.put("code",1);
        map.put("msg", "success");
        return new JSONObject(map).toString();

    }

    @ResponseBody
    @RequestMapping(value = "/submitOrder.json", produces = "application/json;charset=UTF-8")
    public String submitOrder(String companyCode,String token,  String seckillGoodsId, Integer addressId,  String memo, Integer deliveryType, Integer storeId, Integer payType) {
        Map<String, Object> map = new HashMap<String, Object>();

        if(!activityService.SeckillActivityState(companyCode)){
            map.put("code", 0);
            map.put("msg", "秒杀活动已停止");
            return new JSONObject(map).toString();
        }
        Address address = null;
        if (StringUtils.isEmpty(token)) {
            map.put("code", -1);
            map.put("msg", "token参数不能为空");
            return new JSONObject(map).toString();
        }
        User loginUser = userDao.getByToken(token);
        if (loginUser == null) {
            map.put("code", -1);
            map.put("msg", "请登录");
            return new JSONObject(map).toString();
        }

        if (StringUtils.isEmpty(deliveryType)) {
            map.put("code", 0);
            map.put("msg", "无发货方式");
            return new JSONObject(map).toString();
        }
        if (StringUtils.isEmpty(payType)) {
            map.put("code", 0);
            map.put("msg", "请选择支付方式");
            return new JSONObject(map).toString();
        }
        if(deliveryType==2){
            if (addressId == null) {
                map.put("code", 3);
                map.put("msg", "您还未设置地址请先设置地址");
                return new JSONObject(map).toString();
            } else {
                //判断地址是否有效
                address = addressDao.getById(addressId);

                if (address == null) {
                    map.put("code", 0);
                    map.put("msg", "您的地址无效");
                    return new JSONObject(map).toString();
                } else if (address.getUserId()-loginUser.getId()!=0) {
                    map.put("code", 0);
                    map.put("msg", "userid:" + loginUser.getId() + "没有地址id:" + addressId);
                    return new JSONObject(map).toString();
                }

            }
        }

        if (!NumberUtils.isDigits(seckillGoodsId)) {
            map.put("code", 0);
            map.put("msg", "秒杀商品id不能为空");
            return new JSONObject(map).toString();
        }
        SeckillGoods seckillGoods=seckillGoodsDao.getById(NumberUtils.toInt(seckillGoodsId));
        if(seckillGoods==null){
            map.put("code", 0);
            map.put("msg", "秒杀商品id为"+seckillGoodsId+"的商品未找到");
            return new JSONObject(map).toString();
        }

        if(!seckillGoods.getState()){
            map.put("code", 0);
            map.put("msg", "秒杀商品id为"+seckillGoodsId+"的商品已下架");
            return new JSONObject(map).toString();
        }
        Date current=new Date();
        if(current.getTime()>seckillGoods.getEndTime().getTime()){
            map.put("code", 0);
            map.put("msg", "秒杀商品id为"+seckillGoodsId+"的商品秒杀已结束");
            return new JSONObject(map).toString();
        }
        if(current.getTime()<seckillGoods.getStartTime().getTime()){
            map.put("code", 0);
            map.put("msg", "秒杀商品id为"+seckillGoodsId+"的商品秒杀还未开始");
            return new JSONObject(map).toString();
        }
        if(seckillGoods.getInventory()<=0){
            map.put("code", 0);
            map.put("msg", "秒杀商品id为"+seckillGoodsId+"的商品已秒完");
            return new JSONObject(map).toString();
        }
        DdmShop ddmShop = null;

        //预设一级订单对象
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        String pCode = CodeContent.gCode("p", loginUser.getId());
        purchaseOrder.setMemo(memo);
        purchaseOrder.setCreateTime(new Date());
        if (address!=null){
            purchaseOrder.setAddressDetail(address.getDetail());
            purchaseOrder.setCity(address.getCity());
            purchaseOrder.setPhone(address.getPhone());
            purchaseOrder.setName(address.getName());
        }else{
            purchaseOrder.setName(loginUser.getRealName());
            purchaseOrder.setPhone(loginUser.getPhone());

        }
        purchaseOrder.setCode(pCode);
        purchaseOrder.setDeliveryType(DeliveryType.getByIntValue(deliveryType));
        purchaseOrder.setOrderState(OrderState.Create);
        purchaseOrder.setUserId(loginUser.getId());
        purchaseOrder.setSeckill(true);
        purchaseOrder.setPayType(PayType.getByIntValue(payType));

        //预设二级订单
       /*
       * 由于公司业务问题，所以当前默认为一个主仓库，
       * 根据店铺Id决定此订单归属问题
       * */
        DdmShop wareHouseShop = null;
        try {
            wareHouseShop = ddmShopDao.wareShop();
            if (wareHouseShop == null) {
                map.put("code", 0);
                map.put("msg", "获取的仓库对象为空");
                return new JSONObject(map).toString();
            }
        } catch (Exception e) {
            map.put("code", 0);
            map.put("msg", "获取仓库异常");
            return new JSONObject(map).toString();
        }

        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setOrderState(OrderState.Create);
        String cOrder = CodeContent.gCode("c", loginUser.getId());
        shopOrder.setCode(cOrder);
        shopOrder.setUserId(loginUser.getId());
        shopOrder.setDeliveryType(DeliveryType.getByIntValue(deliveryType));
        shopOrder.setCreateTime(new Date());
        shopOrder.setPurchaseOrderCode(purchaseOrder.getCode());
        shopOrder.setSeckill(true);
        shopOrder.setPayType(PayType.getByIntValue(payType));
        if(StringUtils.isEmpty(storeId)){//表示没有把订单制定到某个门店
            shopOrder.setShopId(wareHouseShop.getId());
        } else {//表示需要把这个订单给某个店铺
            shopOrder.setShopId(storeId);
            ddmShop = ddmShopDao.getById(storeId);
            if (ddmShop == null) {
                map.put("code", 0);
                map.put("msg", "您获取的商店对象不存在");
                return new JSONObject(map).toString();
            }

        }
        //当前默认都是自营
        shopOrder.setType(1);
        //购买订单 购买增值服务个数
        int purchaseOrderServiceNum=0;
        //店铺订单 购买增值服务个数
        int shopOrderServiceNum=0;
        int goodId;
        goodId = seckillGoods.getGoodsId();
        int goodNum=1;
        int gooodSpecificationId = 0;
        gooodSpecificationId = seckillGoods.getGoodsSpecificationId()!=null?seckillGoods.getGoodsSpecificationId():0;
        //处理商品清单
        //从数据库中获取商品对象
        DdmGoods good = ddmGoodsDao.getById(goodId);
        if (good == null) {
            map.put("code", 0);
            map.put("msg", "商品不存在");
            return new JSONObject(map).toString();
        }

        if (good.getState() == false) {
            map.put("code", 0);
            map.put("msg", "商品状态无效");
            map.put("msg", "无效商品");
            return new JSONObject(map).toString();
        }
        BigDecimal totalMoney = new BigDecimal(0);//没有任何优惠需要支付的金钱
        BigDecimal totalPayMoney = seckillGoods.getSeckillPrice();   //实际需要支付的金钱
        //预设3级订单
        GoodsOrder goodsOrder = new GoodsOrder();
          /*
          * 处理规格
          * */
        if (gooodSpecificationId != 0) {//带规格的商品
            GoodSpecification goodSpecification = goodSpecificationDao.getById(gooodSpecificationId);
            if (goodSpecification == null) {
                map.put("code", 0);
                map.put("msg", "商品规格不存在");
                return new JSONObject(map).toString();
            }
            if (goodId != goodSpecification.getGoodId()) {
                map.put("code", 0);
                map.put("msg", "商品和商品规格对象不一致");
                return new JSONObject(map).toString();
            }
            totalMoney=goodSpecification.getMemberPrice();
            goodsOrder.setGoodsSpecificationId(gooodSpecificationId);
            goodsOrder.setDdPrice(goodSpecification.getDdPrice());
        } else {//无规格商品
            goodsOrder.setDdPrice(good.getDdPrice());
            totalMoney=good.getMemberPrice();
        }

        BigDecimal saveMoney=totalMoney.subtract(totalPayMoney);//节省金额
        if(saveMoney.compareTo(new BigDecimal(0))==-1){
            saveMoney=new BigDecimal(0);
        }
        goodsOrder.setOrderState(OrderState.Create);
        goodsOrder.setCreateTime(new Date());
        goodsOrder.setGoodsName(good.getName());
        goodsOrder.setUserId(loginUser.getId());
        goodsOrder.setSeckill(true);
        goodsOrder.setNum(goodNum);
        goodsOrder.setHasLmie(good.getIsImie());
        goodsOrder.setGoodsId(goodId);
        goodsOrder.setSalePrice(seckillGoods.getSeckillPrice());
        goodsOrder.setPurchaseOrderCode(purchaseOrder.getCode());
        goodsOrder.setSaveMoney(saveMoney);
        goodsOrder.setShopOrderCode(shopOrder.getCode());
        goodsOrder.setPayMoney(totalPayMoney);
        goodsOrder.setTotalMoney(totalMoney);
        goodsOrder.setServiceNum(0);
        goodsOrder.setSeckillGoodsId(seckillGoods.getId());
        String iCode = CodeContent.gCode("i", loginUser.getId());
        goodsOrder.setCode(iCode);

        /*
        * 补充二级订单
        * */
        shopOrder.setTotalMoney(totalMoney);
        shopOrder.setSaveMoney(saveMoney);
        shopOrder.setPayMoney(totalPayMoney);
        //shopOrder.setHasComment(false);
        shopOrder.setServiceNum(shopOrderServiceNum);
       /*
       * 补充一级订单
       * */
        purchaseOrder.setTotalMoney(totalMoney);
        purchaseOrder.setSaveMoney(saveMoney);
        purchaseOrder.setPayMoney(totalPayMoney);
        purchaseOrder.setServiceNum(purchaseOrderServiceNum);
        /*
        *  添加三级订单，二级订单，三级订单
        * */
        purchaseOrderService.submitOrder(purchaseOrder, shopOrder, goodsOrder);
        seckillGoodsService.updateInventory(seckillGoods.getId(),FlowType.Reduce);
        Map<String, Object> storeMap = new HashMap<String, Object>();
        map.put("payMoney", purchaseOrder.getPayMoney());
        map.put("pCode", purchaseOrder.getCode());
        map.put("code", 1);
        map.put("msg", "success");
        map.put("payType", payType);
        map.put("deliveryType", deliveryType);
        if (ddmShop != null) {
            map.put("point", ddmShop.getLongitudeAndLatitude());
            map.put("shopAddress", ddmShop.getLocation());
            map.put("shopName", ddmShop.getName());
        }
        return new JSONObject(map).toString();
    }

    /**
     *  我的秒杀订单
     * ffl
     * 2017-12-28 09:24:52
     * @param token
     * @param pageNu
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/seckillOrder.json", produces = "application/json;charset=UTF-8")
    public String seckillOrder(String companyCode,String token,String pageNu){
        String data = null;
        try {
            data = seckillGoodsService.seckillOrder(token, pageNu);
        } catch (Exception e) {
            e.printStackTrace();
            return CodeContent.getModelByCode(0, "查询失败", data);
        }
        return data;
    }


    /** 秒杀活动是否开启
     * ffl
     * 2017-12-28 16:55:42
     * @param companyCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/seckillState.json", produces = "application/json;charset=UTF-8")
    public String seckillOrder(String companyCode){
        String data = null;
        try {
            //data = activityService.getSeckillActivityRedis(companyCode);
            data = seckillGoodsService.indexList(companyCode);
        } catch (Exception e) {
            e.printStackTrace();
            return CodeContent.getModelByCode(0, "查询失败", data);
        }
        return data;
    }

    /** 秒杀活动是否开启
     * ffl
     * 2017-12-28 16:55:42
     * @param companyCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/timeSession.json", produces = "application/json;charset=UTF-8")
    public String timeSession( String companyCode,String sort){
        String data = null;
        try {
            data = seckillGoodsService.timeSession(companyCode,sort);
        } catch (Exception e) {
            e.printStackTrace();
            return CodeContent.getModelByCode(0, "查询失败", data);
        }
        return data;
    }
}
